<template>
	<view class="root-view">
		<view class="device-layout-block">
			<view class="device-layout-mod">
				<view class="device-layout-mhead" v-if="false">
					<evan-steps :active="1" direction="horizontal" primaryColor="#428cff">
						<evan-step></evan-step>
						<evan-step></evan-step>
						<evan-step></evan-step>
					</evan-steps>
					 <!-- <u-steps :list="numList" :current="0" mode="number" active-color="#428cff"></u-steps> -->
				</view>
				<view class="device-layout-mbody">
					<view class="textinfo-box">
						<!-- <view class="textinfo-title" style="color:red">设备的MAC地址{{device_id}}</view> -->
						<!-- <view class="textinfo-title" style="color:red">正在配对的设备的MAC地址{{bssid}}</view> -->
						<view class="textinfo-title">请选择设备工作的WI-FI</view>
						<view class="textinfo-desc">此设备只支持家中使用2.4GHz Wi-Fi连接使用Wi-Fi名称仅支持英文字符及数字,请先确保手机端已连接2.4G的wifi</view>
					</view>
					<view class="uform-box u-p-b-64">
						<u-form class="u-border-top" :model="form" ref="uForm">
							<u-form-item left-icon="wifi">
								<u-input v-model="form.wifiName" type="text" :disabled="true" placeholder="请连接Wi-Fi" />
								<!-- <u-button size="mini" type="success" @click="getWifiName()">扫描WIFI</u-button> -->
							</u-form-item>
							<u-form-item left-icon="lock-fill">
								<u-input v-model="form.wifiPassword" type="password" placeholder="输入WIFI密码" />
							</u-form-item>
						</u-form>
					</view>
				</view>
				<view class="device-layout-mfoot ">
					<view class="device-layout-btns">
						<view class="btn-cell">
							<button class="coco-btn theme round lg shadow" @click="setWifi();" :disabled="disabled">开始配网</button>
							<!-- <button class="coco-btn theme round lg shadow" @click="getDeviceStatus();">设备状态</button> -->
						</view>
					</view>
				</view>
			</view>
		</view>
		
	</view>
</template>

<script>
	const espBluFiModule = uni.requireNativePlugin("XM-EspBlufiModule");
	import evanStep from '@/components/evan-steps/evan-step.vue';
	export default {
		components:{
			evanStep
		},
		data() {
			return {
				numList: [{
					name: '滤芯'
				}, {
					name: 'WIFI'
				}, {
					name: '设备'
				} ],
				form: {
					wifiName: '',
					wifiPassword: '',
				},
				gbWifi:null,
				bssid:'',
				disabled:false,
				device_id:'',
				configSuccess:false,
				statusVal:0,
				checkTimes:0,
				isTip:0,
				isBindTip:false,
				wifiLists: []
			};
		},
		onLoad(opt) {
			this.device_id = opt.device_id ? opt.device_id : '';
			// this.gbWiFi = uni.requireNativePlugin('Gl-WiFi'); 
			// this.connectDevice();
			this.getWifiName();
			uni.onGetWifiList(resW => {
				console.log("getwifilist", resW);
				if (resW.wifiList && resW.wifiList.length) {
					this.wifiLists = resW.wifiList;
					uni.offGetWifiList();
					this.getWifiNames();
					// this.getWifiName();
				}
			})
		},
		onUnload() {
			this.disconnectDevice();
		},
		methods:{
			jump(path) {
				this.$tools.routerTo(path);
			},
			scanWifi() {
				uni.getWifiList({
					success: (res) => {
						console.log("wifiList", res);
					}
				});
			},
			connectDevice(){
				let address = uni.getStorageSync("deviceMac");
				if(!address){
					uni.showLoading();
					uni.showModal({
						title:"系统提醒",
						content:"设备地址错误，请核实是否是正确的设备",
						showCancel:false,
						success: (tipRes) => {
							uni.redirectTo({
								url:"/pages/device/bluetooth"
							})
						}
					})
					return false;
				}
				espBluFiModule.connect({
					mac: address, //Android使用
					// uuid: '8AC95EA6-3D7C-C475-07D0-3A2C5400047D' //iOS使用
				}, (ret) => {
					console.log(ret);
					if(ret.success){
						//连接状态信息和接受到的信息回调于此
						// this.getWifiName();
					}
					else{
						uni.hideLoading();
						this.$u.toast(ret.msg);
					}
				});
			},
			disconnectDevice(){
				espBluFiModule.disconnectGatt((ret) => {
					uni.hideLoading();
					if(ret.success){
					}
					else{
						this.$u.toast(ret.msg);
					}
					console.log(ret);
				});
			},
			getWifiName(){
				uni.showLoading({
					title: "正在获取wifi信息"
				});
				uni.startWifi({
					success:(res) => {
						console.log(res);
						// this.getWifiNames();
						this.scanWifi();
					},
					error:(resErr) => {
						uni.hideLoading();
					}
				})
			},
			getWifiNames() {
				uni.getConnectedWifi({
					success: (res) => {
						console.log("wifi参数", res);
						uni.hideLoading();
						if (!res.errCode) {
							let frequency = parseInt(res.wifi.frequency) / 1000;
							console.log(frequency);
							let is5G = true;
							this.wifiLists.forEach((witem, windex) => {
								if (witem.sSID == res.wifi.SSID) {
									var frequencys = parseInt(witem.frequency) / 1000;
									if (frequencys.toFixed(1) == '2.4') {
										is5G = false;
									}
								}
							})
							if (is5G) {
								if (!this.isTip) {
									this.isTip = true;
									this.$u.toast("当前连接的Wi-Fi是5GHz的，请切换到2.4GHz后重试")
								}
							} else {
								this.form.wifiName = res.wifi.SSID;
								uni.stopWifi({
									success: (resStop) => {
										console.log(resStop);
									}
								});
								this.connectDevice();
							}
						}
					},
					error: (resErr) => {
						uni.hideLoading();
					}
				});
				// uni.getWifiList({
				// 	success:(res) => {
				// 		console.log("wifiList",res);
				// 	}
				// });
			},
			setWifi(){
				if(!this.form.wifiName){
					this.$u.toast("连接的Wi-Fi名称不能为空！");
					return false;
				}
				// if(this.disabled){
				// 	return ;
				// }
				// console.log(this.disabled);
				uni.showLoading({
					title:"正在配网，请稍后...."
				});
				
				espBluFiModule.configure({
					deviceMode:1, //OP_MODE_NULL不需要参数
					ssid:this.form.wifiName, //WIFI名称，OP_MODE_STA和OP_MODE_STASOFTAP需要，需要时不能为空
					password:this.form.wifiPassword, //WIFI密码，可空
					ap_ssid:'', //OP_MODE_SOFTAP模式需要，不能为空
					ap_password:'', //security不为SOFTAP_SECURITY_OPEN时，需要大于等于8位
					channel:1, //1-13任意值
					maxConnection:5, //最大连接数
					security:0,
				},(ret) =>{
					if(ret.success){
						this.statusVal = setInterval(() => {
							this.checkTimes++;
							this.getDeviceStatus();
						},1000);
						console.log(ret);
					}
					else{
						uni.hideLoading();
						this.$u.toast(ret.msg);
					}
				});
				
				// this.bindDevice('d2:8d:0d:80:10:ca');
				// this.gbWiFi.startEsptouch(
				// 	{
				//         ssid: this.form.wifiName,
				//         pwd: this.form.wifiPassword,
				//         broadcast: 1,
				// 		bssid:this.bssid
				//     },
				//     result => {
				// 		uni.hideLoading();
				// 		console.log(result);
				// 		if(result.code == 1){
				// 			this.bindDevice(result);
				// 		}
				// 		else{
				// 			this.$u.toast(result.result);
				// 		}
				// });
			},
			bindDevice(){
				let address = uni.getStorageSync("deviceMac");
				// result.device_id = this.device_id;
				// result.mac = address;
				if(this.isBindTip){
					return false;
				}
				this.isBindTip = true;
				this.$post("api/member/bind_equipment",{bssid:address},'',false).then(res => {
					if(res.code == 1){
						this.$u.toast("恭喜你，设备配网并绑定成功！");
						if(!this.device_id){
							setTimeout(()=>{
								uni.redirectTo({
									url:"/pages/device/bind-device"
								})
							},1500);
						}
						else{
							setTimeout(()=>{
								uni.redirectTo({
									url:"/pages/index/devices"
								})
							},1500);
						}
					}
					else{
						this.isBindTip = false;
						this.$u.toast(res.msg);
					}
				})
			},
			getDeviceStatus(){
				espBluFiModule.requestDeviceStatus((ret) => {
					//接口调用信息回调于此
					console.log(ret);
					if(ret.success){
						if(ret.data.response.Station == 'connect Wi-Fi now'){
							uni.hideLoading();
							this.configSuccess = true;
							clearInterval(this.statusVal);
							console.log("配网成功");
							this.bindDevice();
						}
						else{
							if(this.checkTimes > 30){
								uni.hideLoading();
								this.configSuccess = false;
								clearInterval(this.statusVal);
								this.$u.toast("配网失败，请检查wifi密码是否正确");
							}
						}
					}
					else{
						this.$u.toast(ret.msg);
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	@import "./css/device.scss";
	 
</style>
